package cn.com.yx.ms.service.impl;

import cn.com.yx.ms.application.web.ApiPager;
import cn.com.yx.ms.application.web.ApiQueryBase;
import cn.com.yx.ms.domain.TestModel;
import cn.com.yx.ms.domain.TreeModel;
import cn.com.yx.ms.domain.dbmodel.SysLog;
import cn.com.yx.ms.persistence.SysLogMapper;
import cn.com.yx.ms.persistence.TestMapper;
import cn.com.yx.ms.service.ILogService;
import cn.com.yx.ms.service.ITestService;
import cn.yx.framework.configuration.BaseConstant;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.ibatis.io.ResolverUtil;
import org.springframework.boot.bind.YamlConfigurationFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.reflect.generics.tree.Tree;

import javax.annotation.Resource;
import java.io.*;
import java.net.URL;
import java.util.*;

/**
 * ApphubServiceImpl
 */
@Service
@Transactional
public class LogServiceImpl implements ILogService {

    @Resource
    private SysLogMapper sysLogMapper;
    @Resource
    private BaseConstant baseConstant;


    @Override
    public SysLog findOne(String id) {
        return sysLogMapper.selectByPrimaryKey(id);
    }

    @Override
    public int insert(SysLog sysLog) {
        return sysLogMapper.insert(sysLog);
    }

    @Override
    public int delete(String id) {
        return sysLogMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int update(SysLog sysLog) {
        return sysLogMapper.updateByPrimaryKey(sysLog);
    }


    @Override
    public List<SysLog> find(ApiQueryBase query) {
        return sysLogMapper.find(query);
    }

    @Override
    public int log(String type, String module, String content, String userid) {
        SysLog sysLog = new SysLog();
        sysLog.setGuid(UUID.randomUUID().toString());
        sysLog.setType(type);
        sysLog.setModule(module);
        sysLog.setContent(content);
        sysLog.setUserid(userid);
        sysLog.setCreatetime(new Date());
        return insert(sysLog);
    }
    @Override
    public List<TreeModel> findCommandPusthLogs(String path){
        File file = new File(path);
        List<TreeModel> stringList=new ArrayList<TreeModel>();
        TreeModel treeModel=new TreeModel();
        treeModel.setName("logs");
        treeModel.setId("logs");
        treeModel.setIsParent("true");
        treeModel.setChildren(new ArrayList<TreeModel>());
        ergodic(file,treeModel);
        stringList.add(treeModel);
        return stringList;
    }

    private void ergodic(File file,TreeModel treeModel){
        List<TreeModel> list=new ArrayList<TreeModel>();
        File[] files = file.listFiles();
        if(files==null){
            return;// 判断目录下是不是空的
        }
        for (File f : files) {
            if(f.isDirectory()){// 判断是否文件夹
                //
                // System.out.println("文件夹:"+f.getName());
                TreeModel treeModel1=new TreeModel();
                treeModel1.setName(f.getName());
                treeModel1.setId(treeModel.getId()+"//"+f.getName());
                treeModel1.setIsParent("true");
                treeModel1.setChildren(new ArrayList<TreeModel>());
                treeModel.getChildren().add(treeModel1);
                ergodic(f,treeModel1);// 调用自身,查找子目录
            }
        }
    }

    /**
     * 查出文件夹下,所有日志文件信息
     * @param query
     * @return
     */
    @Override
    public List<TreeModel> findComPushLogs(ApiQueryBase query){
        List<TreeModel> stringList=new ArrayList<TreeModel>();
        //找到该文件夹
        File file = new File(query.getConditions().get("compushlogs").toString());
        ergodic2(file,stringList);
        testComparatorSortName(stringList);
        return stringList;
    }

    /**
     * 找到对应文件夹下所有的文件信息
     * @param file
     * @param stringList
     */
    @Override
    public void ergodic2(File file,List<TreeModel> stringList){
        //取到url地址
//        String url=baseConstant.serverConfig().getUrl();
        String url=baseConstant.serverConfig().getMediaurl();
        File[] files = file.listFiles();
        if(files==null){
            return;// 判断目录下是不是空的
        }
        for (File f : files) {
            if(f.isDirectory()){// 判断是否文件夹
                ergodic2(f,stringList);// 调用自身,查找子目录
            }else{
                TreeModel treeModel=new TreeModel();
                treeModel.setName(f.getName());//添加文件名称
                treeModel.setNodetype("0");
                treeModel.setId(url+"/"+f.getPath().replace("/usr/local/nginx/resources/",""));//添加文件地址
                stringList.add(treeModel);//添加进集合
            }
        }
    }
    public void testComparatorSortName(List<TreeModel> list){
        Collections.sort(list,new Comparator () {
            @Override
            public int compare(Object o1, Object o2) {
                if(o1 instanceof TreeModel && o2 instanceof TreeModel){
                    TreeModel e1 = (TreeModel) o1;
                    TreeModel e2 = (TreeModel) o2;
                    return e2.getName().compareTo(e1.getName());
                }
                throw new ClassCastException("不能转换为TreeModel类型");
            }
        });
    }

    @Override
    public List<String> findLogBypath(String path){
        List<String> stringList=new ArrayList<String>();
        stringList=readLog(path);
        return stringList;
    }

    /**
     * 读取单个文件的方法
     * @param filePath
     * @return
     */
    public List<String> readLog(String filePath) {
        List<String> list = new ArrayList<String>();
        try {
            FileInputStream is = new FileInputStream(filePath);
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            try {
                while ((line = br.readLine()) != null) {
                    if (line.equals(""))
                        continue;
                    else
                        list.add(line);
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("读取一行数据时出错");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("文件读取路径错误FileNotFoundException");
        }
        return list;
    }
}